<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="name" label="微生物名称">
          <el-input
            v-model="queryParams.name"
            placeholder="微生物名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button type="success" @click="openDialog()"
          ><i class="el-icon-circle-plus"></i> 新增</el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i class="el-icon-delete"></i> 删除</el-button>
      </template>

      <el-table
        v-loading="loading"
        :data="dataList"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" prop="dataIndex"/>
        <el-table-column label="物种" prop="speciesText"/>
        <el-table-column label="组织" prop="tissueText"/>
        <el-table-column label="实验方法" prop="methodText"/>
        <el-table-column label="所属文献" prop="publicationDto.articleTitle"/>
        <el-table-column label="微生物" prop="organismDto.name"/>
        <el-table-column label="关联对象类型" prop="organismCorrelationTypeText"/>
        <el-table-column label="关联对象" prop="organismCorrelationName"/>
        <el-table-column fixed="right" label="操作"  min-width="280" width="280">
          <template #default="scope">
            <el-button
              type="warning"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            ><i class="el-icon-edit"></i> 编辑</el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            ><i class="el-icon-delete"></i> 删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 微生物表单弹窗 -->
    <el-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      width="750px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="userFormRef" :inline="true"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="物种" prop="species">
          <el-select v-model="formData.species" placeholder="请输入物种">
            <el-option
              v-for="item in speciesList"
              :key="item.id"
              :label="item.value"
              :value="item.secondName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="组织" prop="tissue">
          <el-select v-model="formData.tissue" placeholder="请输入组织">
            <el-option
              v-for="item in tissueList"
              :key="item.id"
              :label="item.value"
              :value="item.secondName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="实验方法" prop="method">
          <el-select v-model="formData.method" placeholder="请输入实验方法">
            <el-option
              v-for="item in methodList"
              :key="item.id"
              :label="item.value"
              :value="item.secondName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属文献" prop="publicationId">
          <el-select v-model="formData.publicationId" 
            filterable
            remote
            :remote-method="publicationRemoteMethod"
            :loading="publicationLoading"
            placeholder="请输入所属文献">
            <el-option
              v-for="item in publicationList"
              :key="item.id"
              :label="item.articleTitle"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="微生物" prop="organismId">
          <el-select v-model="formData.organismId"
            filterable
            remote
            :remote-method="organismRemoteMethod"
            :loading="organismLoading"
            placeholder="请输入微生物">
            <el-option
              v-for="item in organismList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联对象类型" prop="method">
          <el-select v-model="formData.organismCorrelationType" placeholder="请输入关联对象类型">
            <el-option label="基因" value="GENE"></el-option>
            <el-option label="饮食" value="DIET"></el-option>
            <el-option label="代谢物" value="METABOLIN"></el-option>
            <el-option label="表型" value="PHENOTYPE"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联对象" prop="organismCorrelationId" v-if="formData.organismCorrelationType">
          <el-select v-model="formData.organismCorrelationId" 
            filterable
            remote
            :remote-method="organismCorrelationRemoteMethod"
            :loading="organismCorrelationLoading"
            placeholder="请输入关联对象">
            <el-option
              v-for="item in organismCorrelationList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import experimentApi from '@/api/knowledge/experiment'
import organismApi from '@/api/knowledge/organism'
import publicationApi from '@/api/knowledge/publication'
import organismCorrelationApi from '@/api/knowledge/organismCorrelation'
import dictApi from '@/api/system/dict'
import { formatDate } from '@/utils/formatTime'
export default {
	name: 'dictIndex',
	data() {
		return {
			queryParams: {
        name: '',
        pageNum: 0,
        pageSize: 10,
      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      dialog: {},
      formData: {},
      rules: {},

      speciesList: [],
      tissueList: [],
      methodList: [],
      publicationList: [],
      organismList: [],
      organismCorrelationList: [],
      organismCorrelationMap: {},

      organismLoading: false,
      publicationLoading: false,
      organismCorrelationLoading: false,

      speciesMap: {},
      tissueMap: {},
      methodMap: {},
      organismCorrelationTypeMap: {
        PHENOTYPE: '表型',
        GENE: '基因',
        METABOLIN: '代谢物',
        DIET: '饮食',
      },
		};
	},
  mounted () {
    dictApi.listByKey("EXPERIMENT_SPECIES").then(res => {
      this.speciesList = res.data;
      this.speciesList.forEach(v => {
        this.speciesMap["EXPERIMENT_SPECIES_" + v.secondName] = v.value
      })
    });
    dictApi.listByKey("EXPERIMENT_TISSUE").then(res => {
      this.tissueList = res.data;
      this.tissueList.forEach(v => {
        this.tissueMap["EXPERIMENT_TISSUE_" + v.secondName] = v.value
      })
    });
    dictApi.listByKey("EXPERIMENT_METHOD").then(res => {
      this.methodList = res.data;
      this.methodList.forEach(v => {
        this.methodMap["EXPERIMENT_METHOD_" + v.secondName] = v.value
      })
    });
  },
  methods: {
    organismCorrelationRemoteMethod (search) {
      if (search !== '') {
        this.organismCorrelationLoading = true;
        organismCorrelationApi.page({
          number: 1,
          size: 15,
          name: search,
          type: this.formData.organismCorrelationType,
        }).then(res => {
          this.organismCorrelationList = res.data.content;
          this.organismCorrelationList.forEach(element => {
            this.organismCorrelationMap[element.id] = element.name;
          });
          this.organismCorrelationLoading = false;
        });
      } else {
        this.organismCorrelationList = [];
        this.organismCorrelationMap = {};
      }
    },
    publicationRemoteMethod (search) {
      if (search !== '') {
        this.publicationLoading = true;
        publicationApi.page({
          number: 1,
          size: 15,
          name: search,
        }).then(res => {
          this.publicationList = res.data.content;
          this.publicationLoading = false;
        });
      } else {
        this.publicationList = [];
      }
    },
    organismRemoteMethod (search) {
      if (search !== '') {
        this.organismLoading = true;
        organismApi.page({
          number: 1,
          size: 15,
          name: search,
        }).then(res => {
          this.organismList = res.data.content;
          this.organismLoading = false;
        });
      } else {
        this.organismList = [];
      }
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        name: this.queryParams.name,
      };
      experimentApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.speciesText = this.speciesMap["EXPERIMENT_SPECIES_" + v.species]
          v.tissueText = this.tissueMap["EXPERIMENT_TISSUE_" + v.tissue]
          v.methodText = this.methodMap["EXPERIMENT_METHOD_" + v.method]
          v.organismCorrelationTypeText = this.organismCorrelationTypeMap[v.organismCorrelationType]
          v.dataIndex = index++;
        });
        this.dataList = data.content;
        
        this.total = data.count;
        this.loading = false;
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
      };
      this.handleQuery();
    },
    
    addOrUpdate() {
      let that = this;
      if (this.formData.organismCorrelationId) {
        this.formData.organismCorrelationName = this.organismCorrelationMap[this.formData.organismCorrelationId];
      }
      if (this.formData.id) {
        experimentApi.update(this.formData).then((res) => {
          this.$message({message: '文献实验更新成功！', type: 'success'});
          that.closeDialog();
        });
      } else {
        experimentApi.add(this.formData).then((res) => {
          this.$message({message: '文献实验添加成功！', type: 'success'});
          that.closeDialog();
        });
      }
    },
    openDialog(id) {
      this.$set(this.dialog, 'visible', true);
      let that = this;
      if (id) {
        this.$set(this.dialog, 'title', '编辑文献实验');
        experimentApi.get(id).then((res) => {
          let data = res.data;
          that.formData = data;

        });
      } else {
        this.$set(this.dialog, 'title', '新增文献实验');
        that.formData = {};
      }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        experimentApi.delete(id).then((res) => {
          this.$message({message: '文献实验删除成功！', type: 'success'});
          this.handleQuery();
        });
      } else {
        this.$message.error('暂不支持批量删除文献实验！');
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    this.handleQuery();
  }
};
</script>

<style scoped>
.el-pagination {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}
</style>